//
//  JMeViewController.m
//  HeadIndustry
//
//  Created by jun on 2017/8/24.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JMeViewController.h"
#import "JButton.h"
#import "JMessageBtn.h"

#import "JOrderController.h"
#import "JSettingController.h"
#import "JUserInfoController.h"
#import "JMyCollectController.h"

#import "JPersonageController.h" // 个人主页
#import "JAbouttingController.h" // 关于我们
#define btntag 10
#define labelTag 20
#define viewTag 50

@interface JMeViewController ()

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *btnView;

@property (nonatomic, strong) NSMutableArray *msgbtnNumArr;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *headImgBtn;
@property (nonatomic, strong) YYLabel *userName;
@property (nonatomic, strong) JMessageBtn *messageBtn;


@end

@implementation JMeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [super InitUI];
    
    self.titleLabel.text = @"个人中心";
    self.leftButton.hidden = YES;
    self.rightButton.hidden = YES;
    self.contentView.backgroundColor = kRGBColor(240, 240, 240);
    
    _msgbtnNumArr = [NSMutableArray array];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, CGRectGetHeight(self.contentView.frame)-49)];
    [self.contentView addSubview:_scrollView];
    
    // 加载用户信息
    [self loadUserInfoRequest];
    
    // 创建上面的用户信息View
    [self configBGView];
    
    // 创建账单按钮 和下面的选择项
    [self createBtnMethod];
    
    // 获取账单数量
    [self loadUserOrderRequest];
    
    // 监听账单编号
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiOrderChange) name:NSStringFromClass([JOrderController class]) object:nil];
}

- (void)notiOrderChange
{
    // 获取账单数量
    [self loadUserOrderRequest];
}

- (void)configBGView {
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, 76 + 20)];
    topView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:topView];
    _topView = topView;
    
    UIButton *btnImg = [UIButton buttonWithType:UIButtonTypeCustom];
//    [btnImg setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    btnImg.imageView.contentMode = UIViewContentModeScaleAspectFit;
    btnImg.frame = CGRectMake(15, 10, 76, 76);
    btnImg.layer.cornerRadius = 76/2.0;
    btnImg.layer.masksToBounds = YES;
   
    [btnImg addTarget:self action:@selector(btnImgClick:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:btnImg];
    _headImgBtn = btnImg;
    
    YYLabel *nameLa = [YYLabel new];
    nameLa.frame = CGRectMake(btnImg.right+10, 10, kWindowW - btnImg.right -  10 - 50, 30);
    nameLa.font = kFONT_TITLE(16);
    [topView addSubview:nameLa];
    _userName = nameLa;
    
    _messageBtn = [[JMessageBtn alloc]initWithFrame:CGRectMake(kWindowW - 10 - 40, 10, 40, 30)];
    [_messageBtn addTarget:self action:@selector(msgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:_messageBtn];
}

- (void)createBtnMethod {
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, _topView.height + 10, kWindowW, 80)];
    topView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:topView];
    _btnView = topView;
    
    NSArray *namearr = @[@"待付款",@"待收货",@"待评论",@"退换货",@"已结束"];
    NSArray *imgArr = @[@"payments",@"send",@"assess",@"return",@"all"];
    
    CGFloat btnWidth = kWindowW /5.0;
    for (int i = 0; i < 5; i++) {
        JButton *btn = [JButton buttonWithType:UIButtonTypeCustom frame:CGRectMake(i * btnWidth, 5, btnWidth, 70) title:namearr[i] titleColor:[UIColor blackColor] titleFont:16 textAlignment:NSTextAlignmentCenter image:imgArr[i] imageViewContentMode:UIViewContentModeCenter tag:btntag + i imageURL:nil handler:^(UIButton *sender) {
            [self selBtnClick:sender];
        }];
        
        YYLabel *label = [YYLabel new];
        label.frame = CGRectMake(btnWidth - 19 * 2, 3 , 16, 16);
        label.layer.cornerRadius = 8;
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        label.backgroundColor = [UIColor redColor];
        label.text = @"0";
        [btn addSubview:label];
        label.tag = labelTag + i;
        label.hidden = YES;
        [_msgbtnNumArr addObject:label];
        [topView addSubview:btn];
    }
    
    CGRect rect1 = CGRectMake(0, topView.bottom + 10, kWindowW, 40);
    UIView *view1 = [self setViewRect:rect1 title:@"个人主页" num:viewTag imgname:@"2_quanzi"];
    
    CGRect rect2 = CGRectMake(0, view1.bottom + 10, kWindowW, 40);
    UIView *view2 = [self setViewRect:rect2 title:@"我的收藏" num:viewTag+1 imgname:@"2_shoucang_icon"];
    
    CGRect rect3 = CGRectMake(0, view2.bottom, kWindowW, 40);
    UIView *view3 = [self setViewRect:rect3 title:@"商家入驻" num:viewTag+2 imgname:@"2_footprink"];
    
    CGRect rect4 = CGRectMake(0, view3.bottom + 10, kWindowW, 40);
    UIView *view4 = [self setViewRect:rect4 title:@"关于我们" num:viewTag+3 imgname:@"tel"];
    
    CGRect rect5 = CGRectMake(0, view4.bottom, kWindowW, 40);
    [self setViewRect:rect5 title:@"设置" num:viewTag+4 imgname:@"2_set"];
    
}

- (UIView *)setViewRect:(CGRect)rect title:(NSString *)title num:(NSInteger)num imgname:(NSString *)imgName
{
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.opaque = NO;
    view.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:view];
    
    UITapGestureRecognizer *tapgesture = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        switch (num) {
            case 50:
            {
                //                NSLog(@"进入个人主页");
                JPersonageController *orderVC = [[JPersonageController alloc]init];
                orderVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:orderVC animated:YES];
            }
                
                break;
            case 51: // 收藏
            {
                JMyCollectController *orderVC = [[JMyCollectController alloc]init];
                orderVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:orderVC animated:YES];
            }
                break;
            case 52:
//                NSLog(@"进入商家入驻");
                [self BusinessSettledMothed];
                break;
            case 53: // 关于我们 
            {
                JAbouttingController *orderVC = [[JAbouttingController alloc]init];
                orderVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:orderVC animated:YES];
            }
                break;
            case 54: // 设置页面
            {
                JSettingController *orderVC = [[JSettingController alloc]init];
                orderVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:orderVC animated:YES];
            }
                break;
                
            default:
                break;
        }
    }];
    [view addGestureRecognizer:tapgesture];
    
    CALayer *imgLayer = [CALayer layer];
    imgLayer.contents = (__bridge id _Nullable)([UIImage imageNamed:imgName].CGImage);
    imgLayer.frame = CGRectMake(15, 12, 16, 16);
    [view.layer addSublayer:imgLayer];
    if (num == 53) {  // 关于我们
        imgLayer.frame = CGRectMake(15, 12, 16, 14);
    }
    
    YYLabel *name = [YYLabel new];
    name.left = imgLayer.right + 10;
    name.top = 0;
    name.size = CGSizeMake(75, view.height);
    name.text = title;
    name.font = kFONT_TITLE(16);
//    name.textColor = kRGBColor(106, 106, 106);
    [view addSubview:name];
    
    CALayer *layer = [CALayer layer];
    layer.contents = (__bridge id _Nullable)([UIImage imageNamed:rightBtnImg].CGImage);
    layer.frame = CGRectMake(kWindowW - 15 - 10, 12, 10, 16);
    [view.layer addSublayer:layer];
    
    return view ;
}


- (void)BusinessSettledMothed
{
    if ([GLOBALDATA userInfoModel].Tel.length > 0) {
        NSString *url = @"BusinessSettled/SendMobileMsg";
        [JNetManager BusinessSettledRequedtUrl:url
                                       success:^(id response) {
                                           [SVProgressHUD showSuccessWithStatus:response];
                                       } failure:^(NSString *err) {
                                           [SVProgressHUD showErrorWithStatus:err];
                                       }];
    }
    else
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有预留手机号，请先完善个人资料" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            JUserInfoController *orderVC = [[JUserInfoController alloc]init];
            orderVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:orderVC animated:YES];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertVC addAction:doneAction];
        [alertVC addAction:cancelAction];
        
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (void)btnImgClick:(UIButton *)btn
{
    JUserInfoController *orderVC = [[JUserInfoController alloc]init];
    orderVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:orderVC animated:YES];
}

- (void)msgBtnClick:(UIButton *)btn
{
    NSLog(@"跳 信息页面");
}

- (void)selBtnClick:(UIButton *)btn
{
    JOrderController *orderVC = [[JOrderController alloc]init];
    orderVC.numPage = btn.tag - btntag;
    orderVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:orderVC animated:YES];
    
//    switch (btn.tag) {
//        case 10:
//            NSLog(@"待付款");
//            break;
//        case 11:
//            NSLog(@"待收货");
//            break;
//        case 12:
//            NSLog(@"待评论");
//            break;
//        case 13:
//            NSLog(@"退换货");
//            break;
//        case 14:
//            NSLog(@"已结束");
//            break;
//            
//        default:
//            break;
//    };
}

/// 获取用户所有类型账单数量信息
- (void)loadUserOrderRequest {
    NSString *url = @"Orders/GetOrdersCount";
    [JNetManager getUserOrderInfoRequestUrl:url
                                 CustumerID:[GLOBALDATA userInfoModel].CustomerId
                                    success:^(id response) {
                                        if (response) {
                                            
                                            JMyAllOrderNumModel *userModel = response;
                                            
                                            [self setBtnsNumMsg:userModel];
                                            
                                        }
                                    } failure:^(NSString *err) {
                                        [SVProgressHUD showErrorWithStatus:err];
                                    }];

}

/// 获取用户信息
- (void)loadUserInfoRequest
{
    NSString *url = @"Customers/GetCustomerById";
    [JNetManager getUserInfoRequestUrl:url
                            CustumerID:[GLOBALDATA userInfoModel].CustomerId
                               success:^(id response) {
                                   if (response) {
                                       JUserInfoModel *userModel = response;
                                       [GLOBALDATA setUserInfoModel:userModel];
                                       
                                       UIImage *headImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:userModel.HeadImg]]];
                                       [_headImgBtn setBackgroundImage:headImg forState:UIControlStateNormal];
                                       
                                       _userName.text = userModel.NickName;
                                   }
                               } failure:^(NSString *err) {
                                   [SVProgressHUD showErrorWithStatus:err];
                               }];
}

- (void)setBtnsNumMsg:(JMyAllOrderNumModel *)model
{
    if (model.msgCount > 0) {
        _messageBtn.numberLabel.hidden = NO;
        _messageBtn.numStr = [NSString stringWithFormat:@"%ld",(long)model.msgCount];
    }
    else
    {
        _messageBtn.numberLabel.hidden = YES;
    }
    
    // 完成
    if (model.finishCount > 0) {
        YYLabel *labvel = _msgbtnNumArr.lastObject;
        labvel.text = [NSString stringWithFormat:@"%ld",model.finishCount];
        labvel.hidden = NO;
    }
    else
    {
        YYLabel *labvel = _msgbtnNumArr.lastObject;
        labvel.hidden = YES;
    }
    
    // 待付款
    if (model.waitPayCount > 0) {
        YYLabel *labvel = _msgbtnNumArr.firstObject;
        labvel.text = [NSString stringWithFormat:@"%ld",model.waitPayCount];
        labvel.hidden = NO;
    }
    else
    {
        YYLabel *labvel = _msgbtnNumArr.firstObject;
        labvel.hidden = YES;
    }
    
    // 待收货
    if (model.waitReceiveCount > 0) {
        YYLabel *labvel = _msgbtnNumArr[1];
        labvel.text = [NSString stringWithFormat:@"%ld",model.waitReceiveCount];
        labvel.hidden = NO;
    }
    else
    {
        YYLabel *labvel = _msgbtnNumArr[1];
        labvel.hidden = YES;
    }
    
    // 待评价
    if (model.waitCommentCount > 0) {
        YYLabel *labvel = _msgbtnNumArr[2];
        labvel.text = [NSString stringWithFormat:@"%ld",model.waitCommentCount];
        labvel.hidden = NO;
    }
    else
    {
        YYLabel *labvel = _msgbtnNumArr[2];
        labvel.hidden = YES;
    }
    
    // 待退货
    if (model.returnCount > 0) {
        YYLabel *labvel = _msgbtnNumArr[3];
        labvel.text = [NSString stringWithFormat:@"%ld",model.returnCount];
        labvel.hidden = NO;
    }
    else
    {
        YYLabel *labvel = _msgbtnNumArr[3];
        labvel.hidden = YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
